package qwe;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Example9_14 {

	public static void main(String args[]) {
		WindowButton win = new WindowButton("猜数字");

	}
}

class WindowButton extends JFrame implements ActionListener {
	int number;
	JLabel hintLabel, timesy;
	JTextField inputGuess;
	JButton buttonGetNumber, buttonEnter;
	private int y;
	private int x;
	private String sj;
	private int time;
	private int op;

	WindowButton(String s) {
		super(s);
		addWindowListener(new WindowAdapter() { // 匿名类的实例监视窗口事件
			public void windowClosing(WindowEvent e) {
				dispose();
			}
		});
		setLayout(new FlowLayout());
		buttonGetNumber = new JButton("得到一个随机数");
		add(buttonGetNumber);
		hintLabel = new JLabel("输入你的猜测：", JLabel.CENTER);
		hintLabel.setBackground(Color.cyan);
		timesy = new JLabel("剩余时间", JLabel.CENTER);
		timesy.setBackground(Color.red);
		inputGuess = new JTextField("0", 10);
		add(hintLabel);
		add(inputGuess);
		add(timesy);
		buttonEnter = new JButton("确定");
		add(buttonEnter);
		buttonEnter.addActionListener(this);
		buttonGetNumber.addActionListener(this);
		setBounds(100, 100, 150, 150);
		setVisible(true);
		validate();

	}

	public void actionPerformed(ActionEvent e) {
		MyThread t1 = new MyThread();

		if (e.getSource() == buttonGetNumber) {
			time = 30;
			number = (int) (Math.random() * 100) + 1;
			hintLabel.setText("输入你的猜测：");

			x = 1;
			t1.start();
			y = 0;
		} else if (e.getSource() == buttonEnter || x == 1) {
			if (y != 1) {
				int guess = 0;
				try {
					guess = Integer.parseInt(inputGuess.getText());
					if (guess == number) {
						hintLabel.setText("猜对了！");
						x = 0;
					} else if (guess > number) {
						hintLabel.setText("猜大了！");
						inputGuess.setText(null);
					} else if (guess < number) {
						hintLabel.setText("猜小了！");
						inputGuess.setText(null);
					}
				} catch (NumberFormatException event) {
					hintLabel.setText("请输入数字字符");
				}

			} else if (y == 1) {
				hintLabel.setText("你输了！");
				x = 0;
			}
		}

	}

	class MyThread extends Thread {
		public void run() {
			while (time > 0) {
				time--;
				try {
					Thread.sleep(1000);
					sj = String.valueOf(time);
					timesy.setText(sj);
					System.out.println(sj);

				} catch (InterruptedException e1) {

					e1.printStackTrace();
				}
			}
			if (time == 0) {
				y = 1;
			}
		}
	}
}